<?php
/**
 * Created by IntelliJ IDEA.
 * User: Fiend
 * Date: 13-10-13
 * Time: 下午6:47
 * To change this template use File | Settings | File Templates.
 */
/**
 * 手动扩展的控制器
 * Class MY_Controller
 */
class MY_Controller extends CI_Controller {
    /**
     * 输出json
     * @param $v
     * @param bool $en 是否转换编码
     */
    protected function returnjson($v,$en=true){
        $this->output->set_content_type('application/json;charset=UTF-8');
        if($en)
            $this->output->set_output(json_encode($v));
        else
            $this->output->set_output($v);
    }

    /**
     * 发送请求
     * @param $url
     * @param null $headers
     * @param null $data
     * @param string $method
     * @param int $type
     * @return string
     */
    protected function request($url,$headers=null,$data=null, $method='GET',$type=1){
        if($type==1){
            $ch = curl_init($url);
            curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
            if($headers){
                curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
            }
            if($method=='POST'){
                curl_setopt($ch,CURLOPT_POST,1);
                curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
            }
            $resp = curl_exec($ch);
            curl_close($ch);
            return $resp;
        }elseif ($type==2){
            if($method=='GET' && $headers == null){
                return file_get_contents($url);
            }elseif ($headers){
                $aData = array();
                foreach($data as $k=>$v){
                    $aData[] = urlencode($k).'='.urlencode($v);
                }
                $str_data = implode('&',$aData);
                $n = strlen($str_data);
                if($n && $headers){
                    $headers['Content-Length'] = $n;
                }
                $str_headers = '';
                foreach($headers as $k=>$v){
                    $str_headers .= "$k: $v\r\n";
                }
                $opts = array('http'=>array(
                    'method'=>$method,
                ));
                if(strlen($str_headers)){
                    $opts['http']['header'] = $str_headers;
                }
                if($n){
                    $opts['http']['content'] = $str_data;
                }
                $context = stream_context_create($opts);
                return file_get_contents($url,false,$context);
            }
        }
    }
}